<template>
  <el-dialog
      v-model="show"
      title="存储模型设计"
      :show-close="false"
      :close-on-click-modal="false"
      :fullscreen="true"
  >
    <div class="table-design" style="max-height: 90vh;overflow-y: auto;padding: 0px 10px">
      <el-divider content-position="left">存储表信息
        <el-switch
            v-model="automaticTranslationOfTableNames"
            class="ml-2"
            inline-prompt
            style="--el-switch-on-color: #13ce66; --el-switch-off-color: #ff4949"
            active-text="已开启表名自动翻译(点击关闭)"
            inactive-text="已关闭表名自动翻译(点击开启)"
            sise="large"
        ></el-switch>
      </el-divider>

      <div class="layui-form layui-form-pane">
        <div class="layui-row layui-col-space5">
          <div class="layui-col-xs6">
            <div class="layui-form-item ">
              <label class="layui-form-label">存储标题</label>
              <div class="layui-input-block">
                <input type="text" name="title" v-model="form.title" autocomplete="off"
                       placeholder="存储标题"
                       class="layui-input"/>
              </div>
            </div>
            <el-alert :title="form.title_error_msg" v-if="form.title_error" type="error" :closable="false"></el-alert>
          </div>
          <div class="layui-col-xs6">
            <div class="layui-form-item ">
              <label class="layui-form-label">存储表名称</label>
              <div class="layui-input-group">
                <div class="layui-input-prefix layui-input-split ">
                  b_{{ bus.bus_name.replaceAll("-", "_") }}_
                </div>
                <input type="text" name="name" v-model="form.name" autocomplete="off"
                       placeholder="存储表名称"
                       class="layui-input"/>
              </div>
            </div>
            <el-alert :title="form.name_error_msg" v-if="form.name_error" type="error" :closable="false"></el-alert>
          </div>
        </div>
      </div>
      <el-divider content-position="left">字段信息
        <el-switch
            v-model="automaticTranslationOfFields"
            inline-prompt
            style="--el-switch-on-color: #13ce66; --el-switch-off-color: #ff4949"
            active-text="已开启字段自动翻译(点击关闭)"
            inactive-text="已关闭字段自动翻译(点击开启)"
            sise="large"
        ></el-switch>
      </el-divider>
      <div style="padding: 0px 0px 10px 0px;float: right">
        <el-button-group>
          <el-button type="success" :icon="CirclePlus" @click="addField">添加</el-button>
        </el-button-group>
      </div>
      <el-alert :title="form.fieldList_error_msg" v-if="form.fieldList_error" type="error" :closable="false"></el-alert>
      <el-table :data="form.fieldList" type="index" style="width: 100%" :border="true" max-height="50vh"
                ref="fieldList" :scrollbar-always-on="true">
        <el-table-column label="序号" width="80">
          <template #default="scope">
            {{ scope.$index + 1 }}
          </template>
        </el-table-column>
        <el-table-column prop="f_title" label="标题" width="150">
          <template #default="scope">
            <el-input v-model="scope.row.f_title" @input="change_f_title(scope.row)"
                      placeholder="请输入标题"></el-input>
            <el-alert :title="scope.row.f_title_error_msg" v-if="scope.row.f_title_error" type="error"
                      :closable="false"/>
          </template>
        </el-table-column>
        <el-table-column prop="f_name" label="名称" width="150">
          <template #default="scope">
            <el-input v-model="scope.row.f_name" placeholder="请输入名称"></el-input>
            <el-alert :title="scope.row.f_name_error_msg" v-if="scope.row.f_name_error" type="error" :closable="false"/>
          </template>
        </el-table-column>
        <el-table-column prop="f_type" label="类型" width="150">
          <template #default="scope">
            <el-select
                v-model="scope.row.f_type"
                class="m-2"
                placeholder="请选择类型"
                @change="change_f_type(scope.row)"
            >
              <el-option
                  key="varchar"
                  label="字符串"
                  value="varchar"
              ></el-option>
              <el-option
                  key="int"
                  label="整数"
                  value="int"
              ></el-option>
              <el-option
                  key="decimal"
                  label="数值"
                  value="decimal"
              ></el-option>
              <el-option
                  key="datetime"
                  label="日期时间"
                  value="datetime"
              ></el-option>
              <el-option
                  key="longtext"
                  label="大文本"
                  value="longtext"
              ></el-option>
            </el-select>
            <el-alert :title="scope.row.f_type_error_msg" v-if="scope.row.f_type_error" type="error" :closable="false"/>
          </template>
        </el-table-column>
        <el-table-column prop="f_length" label="长度" width="80">
          <template #default="scope">
            <el-input v-model="scope.row.f_length" placeholder="请输入长度"
                      :readonly="scope.row.f_length_readOnly"></el-input>
            <el-alert :title="scope.row.f_length_error_msg" v-if="scope.row.f_length_error" type="error"
                      :closable="false"/>

          </template>
        </el-table-column>
        <el-table-column prop="f_null" label="是否空" width="80">
          <template #default="scope">
            <el-switch
                v-model="scope.row.f_null"
                inline-prompt
                style="--el-switch-on-color: #13ce66; --el-switch-off-color: #ff4949"
                active-text="是"
                inactive-text="否"
                sise="large"
            ></el-switch>
            <el-alert :title="scope.row.f_null_error_msg" v-if="scope.row.f_null_error" type="error" :closable="false"/>
          </template>
        </el-table-column>
        <el-table-column prop="f_desc" label="描述">
          <template #default="scope">
            <el-input v-model="scope.row.f_desc"
                      placeholder="请输入描述"></el-input>
            <el-alert :title="scope.row.f_desc_error_msg" v-if="scope.row.f_desc_error" type="error"
                      :closable="false"/>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="80">
          <template #default="scope">
            <el-button-group>
              <el-button type="danger" :icon="Delete" @click="deleteField(scope.$index)"></el-button>
            </el-button-group>
          </template>
        </el-table-column>
      </el-table>
      <div style="padding-bottom: 10px">
        <el-alert type="success" effect="dark" :closable="false">
          <div style="font-size: 15px">默认字段（请勿重复填写）:id,create_time,update_time,create_user_id,update_user_id
          </div>
        </el-alert>
      </div>
    </div>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="close">取消</el-button>
        <el-button type="primary" @click="save">
          保存
        </el-button>
      </span>
    </template>
  </el-dialog>
</template>
<script>
let time = null;//time用来控制事件的触发
function debounce(fn, delay) {
  return function () {
    if (time !== null) {
      clearTimeout(time);
    }
    time = setTimeout(() => {
      fn.call(this);
      time = null;
      //利用call(),让this的指针从指向window 转成指向input
    }, delay)
  }
}

let {Edit, CirclePlus, Delete} = ElementPlusIconsVue;
let {ElMessageBox, ElMessage} = ElementPlus;
let {toRaw} = Vue;
module.exports = {
  props: ["show", "bus"],
  data() {
    return {
      Edit,
      CirclePlus, Delete,
      automaticTranslationOfTableNames: false,
      automaticTranslationOfFields: false,
      form: {
        title: "",
        name: "",
        fieldList: []
      },
    }
  },
  watch: {
    form_title(newValue, oldValue) {
      let that = this;
      if (that.automaticTranslationOfTableNames) {
        //bus_name 给一个翻译
        debounce(function () {
          if (newValue != '') {
            that.form.name = "自动翻译请稍等...";
            fetch(apiUrlConfig.file.translate, {
              method: 'POST',
              headers: {
                'Content-Type': 'application/x-www-form-urlencoded',
                'Authorization': localStorage.getItem('token')
              },
              body: `text=${encodeURIComponent(newValue)}`
            })
                .then(response => response.json())
                .then(data => {
                  try {
                    that.form.name = data.data.replaceAll("-", "_");
                  } catch (e) {
                    that.form.name = "";
                  }
                })
                .catch(error => console.error('Error:', error));

          } else {
            that.form.name = "";
          }

        }, 500)();
      }

    }
  },
  computed: {
    form_title() {
      return this.form.title;
    }
  },
  methods: {
    close() {
      this.$emit("up-parent", {
        key: "isTableDesign",
        value: false
      }, {eval: "this.$refs.busModelManage.getStorageModelList()"});
    }
    , change_f_type(item) {
      if (item.f_type == "datetime" || item.f_type == "int" || item.f_type == "longtext") {
        item.f_length = "0";
        item.f_length_readOnly = true;
      } else if (item.f_type == "varchar") {
        item.f_length = "255";
        item.f_length_readOnly = true;
      } else if (item.f_type == "decimal") {
        item.f_length = "10,2";
        item.f_length_readOnly = true;
      } else {
        item.f_length = "";
        item.f_length_readOnly = false;
      }
    }
    , change_f_title(item) {
      let that = this;
      if (that.automaticTranslationOfFields) {
        //bus_name 给一个翻译
        debounce(function () {
          if (item.f_title != '') {
            item.f_name = "自动翻译请稍等...";
            fetch(apiUrlConfig.file.translate, {
              method: 'POST',
              headers: {
                'Content-Type': 'application/x-www-form-urlencoded',
                'Authorization': localStorage.getItem('token')
              },
              body: `text=${encodeURIComponent(item.f_title)}`
            })
                .then(response => response.json())
                .then(data => {
                  try {
                    item.f_name = data.data.replaceAll("-", "_");
                  } catch (e) {
                    item.f_name = "";
                  }
                })
                .catch(error => console.error('Error:', error));

          } else {
            item.f_name = "";
          }
        }, 500)();
      }
    }
    , deleteField(index) {
      this.form.fieldList.splice(index, 1);
    }
    , addField() {
      this.form.fieldList = this.form.fieldList == null ? [] : this.form.fieldList
      this.form.fieldList.push({
        f_title: "",
        f_name: "",
        f_type: "",
        f_length: "",
        f_null: true,
        f_length_readOnly: false,
        f_desc:""
      })
      // 跳到底部操作
      // this.$nextTick(() => {
      //   let fieldList = toRaw(this.$refs.fieldList)
      //   debugger
      //   toRaw(fieldList.$refs).bodyWrapper.scrollTop = toRaw(fieldList.$refs).bodyWrapper.scrollHeight
      // });
      //跳到顶部操作
      // this.$refs.containerTable.bodyWrapper.scrollTop =0 //可根据页面高度设置
    }
    , async initConfig() {
      let data = await layui.common.ajax({
        url: apiUrlConfig.sysConfig.getJson,
        type: "get"
      })
      this.automaticTranslationOfFields = data.data.busModelConfg.storageModel.automaticTranslationOfFields
      this.automaticTranslationOfTableNames = data.data.busModelConfg.storageModel.automaticTranslationOfTableNames
    }
    , async save() {
      try {
        this.form.fieldList = (this.form.fieldList == null || this.form.fieldList.length) == 0 ? null : this.form.fieldList
        let data = await layui.common.ajax({
          url: apiUrlConfig.storageModel.add,
          data: JSON.stringify(this.form)
        })
        ElMessage({
          message: '存储模型创建成功',
          type: 'success',
        })
        this.close();
      } catch (e) {
        if (e.status == 10001) {
          ElMessage.error('存储模型新增失败，请检查输入项')
          let error_data = JSON.parse(e.msg);
          for (let key in error_data) {
            if (key.indexOf("[") == -1) {
              this.form[key + "_error"] = true;
              this.form[key + "_error_msg"] = error_data[key];
            } else {
              eval('this.form.' + key + '_error=true');
              eval('this.form.' + key + '_error_msg="' + error_data[key] + '"');
            }
          }
        }
      }
    }
  },
  mounted() {
    this.initConfig();
    this.form.bus_id = this.bus.id;
  }
}
</script>
<style scoped>
.el-dialog__body {
  padding-top: 0px;
}

.el-card__body {
  padding: 5px;
}

.el-alert {
  margin-top: 3px;
}

.layui-form-item {
  margin-bottom: 3px;
}
</style>
